<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" class="!w-1000px" scroll :max-height="600">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="110px"
      v-loading="formLoading"
    >
      <el-form-item label="合同编号" prop="contractNo">
        <el-select v-model="formData.contractNo" filterable placeholder="请选择合同编号">
          <el-option
            v-for="item in ContractList"
            :key="item.contractNo"
            :label="item.contractNo"
            :value="item.contractNo"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="合同名称" prop="contractName">
        <el-input v-model="formData.contractName" disabled placeholder="系统自动获取" />
      </el-form-item>
      <el-form-item label="合同乙方名称" prop="supplierName">
        <el-input v-model="formData.supplierName" disabled placeholder="系统自动获取" />
      </el-form-item>
      <el-form-item label="付款备注" prop="paymentRemark">
        <el-input v-model="formData.paymentRemark" placeholder="请输入付款备注" />
      </el-form-item>
      <ContentWrap>
        <el-form-item prop="detailSaveReqVOS" style="display: none" />
        <el-table :data="formData.detailSaveReqVOS" :stripe="true">
          <el-table-column label="序号" type="index" width="60" />
          <el-table-column label="付款计划编号" align="center" prop="planNo" width="320">
            <template #default="{ row }">
              <el-input v-model="row.planNo" placeholder="系统自动生成" disabled class="!w-300px" />
            </template>
          </el-table-column>
          <el-table-column label="付款期数" align="center" prop="period" width="120">
            <template #default="{ row }">
              <el-input v-model="row.period" type="number" class="!w-100px" />
            </template>
          </el-table-column>
          <el-table-column label="计划付款金额" align="center" prop="planPaymentAmount" width="120">
            <template #default="{ row }">
              <el-input v-model="row.planPaymentAmount" disabled type="number" class="!w-100px" />
            </template>
          </el-table-column>
          <el-table-column label="计划付款日期" align="center" prop="planDate" width="160">
            <template #default="{ row }">
              <el-date-picker
                v-model="row.planDate"
                value-format="YYYY-MM-DD"
                placeholder="计划付款日期"
                class="!w-140px"
              />
            </template>
          </el-table-column>
          <el-table-column label="付款类型" align="center" prop="paymentType" width="160">
            <template #default="{ row }">
              <el-select
                v-model="row.paymentType"
                placeholder="选择付款类型"
                clearable
                class="!w-140px"
              >
                <el-option
                  v-for="dict in getStrDictOptions(DICT_TYPE.PAYMENT_TYPE)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="计划付款比例" align="center" prop="planPaymentRatio" width="140">
            <template #default="{ row }">
              <el-input
                v-model="row.planPaymentRatio"
                type="number"
                class="!w-120px"
                @change="calculatePaymentAmount(row)"
              >
                <template #append>%</template>
              </el-input>
            </template>
          </el-table-column>
          <el-table-column
            label="实际付款状态"
            align="center"
            prop="actualPaymentStatus"
            width="160"
          >
            <template #default="{ row }">
              <el-select
                v-model="row.actualPaymentStatus"
                placeholder="实际付款状态"
                clearable
                class="!w-140px"
              >
                <el-option
                  v-for="dict in getStrDictOptions(DICT_TYPE.ACTUAL_PAYMENT_STATUS)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="实际付款金额" align="center" prop="actualAmount" width="120">
            <template #default="{ row }">
              <el-input v-model="row.actualAmount" type="number" class="!w-100px" />
            </template>
          </el-table-column>
          <el-table-column label="实际付款日期" align="center" prop="actualDate" width="160">
            <template #default="{ row }">
              <el-date-picker
                v-model="row.actualDate"
                value-format="YYYY-MM-DD"
                placeholder="实际付款日期"
                class="!w-140px"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" align="center" min-width="120px">
            <template #default="scope">
              <el-button
                link
                type="danger"
                @click="handleDelete(scope.$index)"
                v-hasPermi="['erp:contract-payment-plan:delete']"
                :disabled="formData.detailSaveReqVOS.length <= 1"
              >
                删除此条
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </ContentWrap>
      <div style="text-align: center">
        <el-button @click="addDetailSaveReqVOS">
          <Icon icon="ep:plus" class="mr-5px" />添加一行
        </el-button></div
      >
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { ContractPaymentPlanApi, ContractPaymentPlanVO } from '@/api/erp/contractpaymentplan'
import { ContractApi, ContractVO } from '@/api/erp/contract'
import { formatDate } from '@/utils/formatTime.js'

/** 合同付款计划 表单 */
defineOptions({ name: 'ContractPaymentPlanForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  planNo: undefined,
  contractId: undefined,
  contractNo: undefined,
  contractName: undefined,
  supplierName: undefined,
  paymentRemark: undefined,
  detailSaveReqVOS: [
    {
      id: undefined,
      paymentPlanId: undefined,
      planNo: undefined,
      period: undefined,
      planDate: undefined,
      paymentType: undefined,
      planPaymentRatio: undefined,
      planPaymentAmount: undefined,
      actualPaymentStatus: undefined,
      actualAmount: undefined,
      actualDate: undefined
    }
  ]
})

// 生成随机ID用于临时标识
const generateTempId = () => {
  return 'temp_' + Math.random().toString(36).substr(2, 9)
}

// 完善表单校验规则
const formRules = reactive({
  contractNo: [{ required: true, message: '合同编号不能为空', trigger: 'blur' }],
  contractName: [{ required: true, message: '合同名称不能为空', trigger: 'blur' }],
  supplierName: [{ required: true, message: '合同乙方名称不能为空', trigger: 'blur' }],
  detailSaveReqVOS: [
    {
      type: 'array',
      required: true,
      message: '至少需要一条付款计划',
      trigger: 'change'
    },
    {
      validator: (rule: any, value: any[], callback: any) => {
        // 校验数组中的每一项
        const errors: string[] = []
        value.forEach((item, index) => {
          if (!item.period) {
            errors.push(`第${index + 1}行：付款期数不能为空`)
          }
          if (!item.planDate) {
            errors.push(`第${index + 1}行：计划付款日期不能为空`)
          }
          if (!item.planPaymentAmount || isNaN(Number(item.planPaymentAmount))) {
            errors.push(`第${index + 1}行：请输入有效的实际付款金额`)
          }
        })

        if (errors.length > 0) {
          callback(new Error(errors.join('；')))
          callback(message.error(errors.join('；')))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ]
})

const formRef = ref() // 表单 Ref

/** 获取合同信息 */
const ContractList = ref([])
const getContractList = async () => {
  try {
    const data = await ContractApi.getContractPage({ pageNo: 1, pageSize: 100 })
    ContractList.value = data.list
  } finally {
  }
}
const contractAmountInclTax = ref(0) // 总金额
watch(
  () => formData.value.contractNo,
  (newVal) => {
    if (!newVal) {
      formData.value.id = undefined
      return
    }
    const matchedContract = ContractList.value.find((item) => item.contractNo === newVal)
    formData.value.contractId = matchedContract ? matchedContract.id : undefined
    formData.value.contractName = matchedContract ? matchedContract.contractName : undefined
    formData.value.supplierName = matchedContract ? matchedContract.partyB : undefined
    contractAmountInclTax.value = matchedContract ? matchedContract.contractAmountInclTax : 0
    // 当合同变化时，重新计算所有明细的金额
    formData.value.detailSaveReqVOS.forEach((row) => {
      calculatePaymentAmount(row)
    })
  },
  { immediate: true, deep: true }
)

/**
 * 根据比例计算计划付款金额
 * @param row 当前行数据
 */
const calculatePaymentAmount = (row) => {
  // 确保合同总金额和比例都存在且有效
  if (contractAmountInclTax.value && row.planPaymentRatio && !isNaN(row.planPaymentRatio)) {
    // 计算：总金额 × 比例 ÷ 100，保留两位小数
    row.planPaymentAmount = Number(
      ((contractAmountInclTax.value * row.planPaymentRatio) / 100).toFixed(2)
    )
  }
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  await getContractList()
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await ContractPaymentPlanApi.getContractPaymentPlan(id)
      // 处理明细数据，转换日期格式
      formData.value.detailSaveReqVOS =
        formData.value.detailRespVOS?.map((item) => {
          return {
            ...item,
            // 将时间戳转换为yyyy-mm-dd格式
            actualDate: item.actualDate ? formatDate(item.actualDate, 'YYYY-MM-DD') : '',
            planDate: item.planDate ? formatDate(item.planDate, 'YYYY-MM-DD') : ''
          }
        }) || []
      delete formData.value.detailRespVOS
      // 如果没有明细数据，初始化一条
      if (!formData.value.detailSaveReqVOS || formData.value.detailSaveReqVOS.length === 0) {
        formData.value.detailSaveReqVOS = [createEmptyDetail()]
      }
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 创建空的明细行 */
const createEmptyDetail = () => {
  return {
    id: generateTempId(),
    paymentPlanId: undefined,
    planNo: undefined,
    period: undefined,
    planDate: undefined,
    paymentType: undefined,
    planPaymentRatio: undefined,
    planPaymentAmount: undefined,
    actualPaymentStatus: undefined,
    actualAmount: undefined,
    actualDate: undefined
  }
}

/** 添加一行 */
const addDetailSaveReqVOS = () => {
  formData.value.detailSaveReqVOS.push(createEmptyDetail())
  // 触发表单校验
  formRef.value?.validateField('detailSaveReqVOS')
}

/** 删除一行 */
const handleDelete = (index: number) => {
  // 至少保留一行
  if (formData.value.detailSaveReqVOS.length <= 1) {
    message.warning('至少保留一条付款计划')
    return
  }
  formData.value.detailSaveReqVOS.splice(index, 1)
  // 触发表单校验
  formRef.value?.validateField('detailSaveReqVOS')
}

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as ContractPaymentPlanVO
    // 移除临时ID并转换日期为时间戳
    data.detailSaveReqVOS = data.detailSaveReqVOS.map((item) => {
      const { id, actualDate, planDate, ...rest } = item
      // 如果是临时ID则不传递，否则保留
      const isTempId = String(id)?.startsWith('temp_')
      // 转换日期为时间戳（毫秒级）
      // 只在日期存在时进行转换
      const processedItem = {
        ...rest,
        ...(actualDate && { actualDate: new Date(actualDate).getTime() }),
        ...(planDate && { planDate: new Date(planDate).getTime() })
      }
      // 如果不是临时ID，需要保留id并更新日期字段
      if (!isTempId) {
        processedItem.id = id
      }
      return processedItem
    })

    if (formType.value === 'create') {
      await ContractPaymentPlanApi.createContractPaymentPlan(data)
      message.success(t('common.createSuccess'))
    } else {
      await ContractPaymentPlanApi.updateContractPaymentPlan(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    planNo: undefined,
    contractId: undefined,
    contractNo: undefined,
    contractName: undefined,
    supplierName: undefined,
    paymentRemark: undefined,
    detailSaveReqVOS: [createEmptyDetail()]
  }
  if (formRef.value) {
    formRef.value.resetFields()
  }
}
</script>
